package it.tukano.io;

/**
 * Utilities for binary data
 * @author pgi
 */
public class BinaryUtilities {

    /**
     * Instance initializer
     */
    BinaryUtilities() {
    }

    /**
     * Converts a sequence of bytes into a sequence of hex digits
     * @param data the bytes to convert
     * @return a sequence of hex digits
     */
    public static String toHexString(byte[] data) {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            buffer.append(String.format("%02X", data[i]));
        }
        return buffer.toString();
    }

    /**
     * Converts a sequence of hex bytes into an array of bytes
     * @param data the data to convert
     * @return the array of bytes
     */
    public static byte[] fromHexString(String data) {
        byte[] bytes = new byte[data.length() / 2];
        for (int i = 0; i < data.length(); i += 2) {
            bytes[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
        }
        return bytes;
    }
}
